package com.cuit.filter;

import com.cuit.constants.Constants;
import com.cuit.extension.Activate;
import com.cuit.factory.SingleFactory;
import com.cuit.limit.FlowController;
import com.cuit.limit.ServiceFlowManager;
import com.cuit.remoting.dto.RpcRequest;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Activate(group = Constants.CONSUMER, order = 2)
public class AccessLimitFilter implements Filter{
    private final ServiceFlowManager serviceFlowManager;

    public AccessLimitFilter() {
        this.serviceFlowManager = SingleFactory.getSingle(ServiceFlowManager.class);
    }

    @Override
    public void doFilter(FilterContext filterContext)throws Exception {
        RpcRequest rpcRequest = filterContext.getRpcRequest();

        log.info("请求id：{},进入限流判断逻辑", rpcRequest.getRequestId());
        serviceFlowManager.callServiceFlow(rpcRequest);

        if (!serviceFlowManager.isAllow(rpcRequest)){
            log.error("服务[{}]超过了客户端最大限流数，停止远程调用", rpcRequest.getRpcServiceName());
            filterContext.setShouldBreak(true);
        }
    }
}
